import { useLocation } from 'react-router-dom';

/**
 * 平级数据转换为树形
 * @param arr 平级数据
 * @param id  节点
 * @param key 父节点
 * @returns 树形
 */
export function flatToNest(arr: any, id = 0, key = 'parent_id') {
  return arr
    .filter((item: any) => item[key] === id)
    .map((item: any) => {
      const children = flatToNest(arr, item.id);
      return children.length ? { ...item, children } : { ...item };
    });
}

/**
 * 解析URL search
 * @param str      要解析的字符串
 * @param isDecode 是否decode
 * @returns {object}
 */
export function parseParam(str: string, isDecode?: boolean) {
  str = str || window.location.search;
  isDecode = isDecode === undefined ? true : isDecode;
  const ary = str.split(/[?&]/),
    result: any = {};
  for (let i = 0, j = ary.length; i < j; i++) {
    const n = ary[i];
    if (!n) continue;
    const tmp = n.split('=');
    result[tmp[0]] = isDecode && !!tmp[1] ? decodeURIComponent(tmp[1]) : tmp[1];
  }
  return result;
}

/**
 * 解析URL search
 * @returns {object}
 */
export function useQuery() {
  return new URLSearchParams(useLocation().search);
}

/**
 * 展开的行
 * @param data      要解析的数据
 * @param key       列表的 key
 * @param children  要解析的子数据
 * @returns {array}
 */
export function expandedRender(data: any, key = 'id', children = 'children') {
  const expandedKeys: any = [];
  const expand = (tree: any) => {
    tree.map((v: any) => {
      if (v[children]) {
        expandedKeys.push(v[key]);
        expand(v[children]);
      }
    });
    return expandedKeys;
  };
  return expand(data);
}
